<?php
// +----------------------------------------------------------------------
// | OneChat
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.tealun.com
// +----------------------------------------------------------------------
// | Author: Tealun Du <tealun@tealun.com> <http://www.tealun.com>
// +----------------------------------------------------------------------
namespace Wechat\Event;

/**
 * 客户文本类型消息处理类
 */
class TextEvent extends BaseEvent {

    /**
     * 对文本类型消息进行处理
     *
     * @param string $openId  客户微信ID唯一识别码
     * @param string $keyword 客户发送的文本信息
     */
    public function textHandle($openId , $keyword)
    {

        /*查看是否有客户缓存*/
        if (S($openId)) {
            if ($reply = A('Wechat/Cache', 'Logic')->cacheReply($openId, $keyword)) {
                return $reply;
            };

        }

        /*TODO 对是否需要验证客户信息的项目进行关键字匹配
        if ($reply = A('Wechat/Pattern', 'Logic') -> findPreg($openId, $keyword)) {
            return $reply;
        }*/

       /* 对关键字进行匹配查询,找到所有对应的关键词组ID */
        //设置用到的参数
        $data['openid'] = $openId;
        $data['action_name'] = 'keyword';
        $data['action_data'] = $keyword;
        //所有关键字统一在Admin模块里设置，所以此处直接调用该模块中的触发关键词回复流
        if ($reply = A('Admin/Reply', 'Event')->reply($data)) {
            return $reply;
        } else {//查询关键字没有结果时，回复信息
            //到事件设置中查找“关键字没有结果”时的回复流程
            $flow = M('TchatEvents')->where('`id` = "4"')->getField('id,flow_id,action_data');
            //查找到相应的回复处理流程
            $reply = M('TchatReplyFlow')->where('`id` = ' . $flow[4]['flow_id'])->find();
            $reply['action_data'] = $flow[4]['action_data'];
            $reply['openid'] = $openId;
            //跨模块调用回复
            return A($reply['module'] . '/' . $reply['controller'], $reply['layer'])->reply($reply);
        }

    }
}
